package com.demo.phonerepair.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.phonerepair.pojo.Repair;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface RepairMapper extends BaseMapper<Repair> {
    @Select(
            """
            SELECT 
                rr.*, 
                u.user_name AS receptionistName  
            FROM yjx_repair_request rr
            LEFT JOIN yjx_user u ON rr.receptionist_id = u.user_id
            LEFT JOIN yjx_user cu ON cu.user_id = #{userId}
            WHERE 1=1
            AND ( cu.role_id IN (1,3) OR rr.user_id = #{userId} )
            AND ( rr.phone_model LIKE CONCAT('%', #{searchKeyword}, '%') 
                  OR rr.phone_issue_description LIKE CONCAT('%', #{searchKeyword}, '%') )
            ORDER BY 
                CASE WHEN #{sortField} = 'createdAt' THEN rr.created_at
                     WHEN #{sortField} = 'requestId' THEN rr.request_id
                     ELSE rr.created_at 
                END ${sortOrder}
            """)

    IPage<Repair> selectRepairByCondition(Page<Repair> page,
                                          @Param("userId") Integer userId,
                                          @Param("searchKeyword") String searchKeyword,
                                          @Param("sortField") String sortField,
                                          @Param("sortOrder") String sortOrder);

    @Delete("""
    DELETE FROM yjx_repair_request
    WHERE request_id = #{repairId} 
    -- 权限过滤，管理员可以删任意（1-3），普通用户只能删除自己创建的 --
    AND ( #{userId} IN (1,3) OR user_id = #{userId} )
            """)
    int deleteRepairByIdAndUserId(
            @Param("repairId") Integer repairId,
            @Param("userId") Integer userId);


    @Select("SELECT * FROM yjx_repair_request WHERE request_id=#{requestId}")
    Repair selectById(Integer requestId);
}